package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func test1() {
	array := [5]string{"I", "am", "stupid", "and", "weak"}
	for i := range array {
		switch i {
		case 2:
			array[2] = "smart"
		case 4:
			array[4] = "strong"
		default:
			continue
		}
	}
	fmt.Println(array)
}

func product(ctx context.Context) {
	t := time.NewTicker(1 * time.Second)

	wgAny := ctx.Value("wg")
	wg := wgAny.(*sync.WaitGroup)
	wg.Done()

	queueAny := ctx.Value("queue")
	queue := queueAny.(*(chan int))
	for _ = range t.C {
		select {
		case <-ctx.Done():
			return
		default:
			(*queue) <- 10
			fmt.Println("输入")
		}
	}
}

func consumer(ctx context.Context) {
	t := time.NewTicker(1 * time.Second)
	wgAny := ctx.Value("wg")
	wg := wgAny.(*sync.WaitGroup)
	wg.Done()

	queueAny := ctx.Value("queue")
	queue := queueAny.(*(chan int))
	for _ = range t.C {
		select {
		case <-ctx.Done():
			return
		default:
			fmt.Println(<-(*queue))
			fmt.Println("输出")
		}
	}
}

func test2() {

}

func main() {
	var wg sync.WaitGroup
	queue := make(chan int, 10)
	done := make(chan bool)
	ctx := context.Background()
	ctx = context.WithValue(ctx, "wg", &wg)
	ctx = context.WithValue(ctx, "queue", &queue)
	ctx = context.WithValue(ctx, "done", &done)
	ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
	wg.Add(1)
	go product(ctx)
	wg.Add(1)
	go consumer(ctx)

	time.Sleep(time.Second * 20)
	wg.Wait()
}
